import modelExtend from "dva-model-extend";
import {viewModel} from "../../../utils/model";
import {setModalInStateForViewUpdate} from "./modal/modalPropertyUtils";
import {getGridOptions} from "../../../common/view/ViewUtils";
import {getRenders} from "../../../common/agGridCellRender/renders";
import {initGridMenuAction, initInSetup, initModalAction, initPanelButtonAction} from "./utils/ModelUtils";

export const commonFlowModel = modelExtend(
  viewModel, {
    state: {
      gridOptions: {
        frameworkComponents: getRenders(),
        withHeader : true
      },
      modalOptions: {
        modalProperties: {
          modalVisible: false
        },
        modalContent: <div>t
        </div>,
        actionOptions: {}
      },
      gridActionOptions: {},
      panelOptions : {
        buttons :[
          {
            name: "Create",
            type: "primary"
          }
        ]
      }
    },
    subscriptions: {
      setup({dispatch, history}) {
        history.listen((location) => {
        })
      },
    },

    reducers: {
      init(state, {payload}){
        initInSetup(state, payload.dispatch);
        return {
          ...state
        }
      },
      querySuccess(state, { payload }){
        if(!payload.rawConfig.success ){
          throw payload.rawConfig
        }

        if(!payload.rawData.success){
          throw payload.rawData
        }

        let viewConfig = payload.rawConfig.list
        let viewData = payload.rawData.list

        const pagination = {
          current: Number(payload.page) || 1,
          pageSize: Number(payload.pageSize) || 10,
          total: viewData.total,
        }

        state.gridOptions = getGridOptions(state.gridOptions, viewConfig, viewData)

        return {
          ...state,
          pagination: {
            ...state.pagination,
            ...pagination,
          },
        }
      },

      showModal: function (state, {payload}) {
        const {action, record} = payload

        setModalInStateForViewUpdate(state.modalOptions, action, record)
        return {...state, ...payload}
      },

      hideModal (state) {
        state.modalOptions.modalProperties["visible"] = false
        return { ...state }
      },
    }
  }
)


